package com.imooc.demo.pingshu;

import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Created by samuelwang on 2020/1/3.
 */
public class DownLoadThread implements Runnable {


    private final String url;
    private final String fileName;
    private final File destFile;


    public DownLoadThread(String url, String fileName) {
        this.url = url;
        this.fileName = fileName;

        File dir = new File("/learndev/javaee/pingshu");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        this.destFile = new File(dir, fileName);
    }


    @Override
    public void run() {
        downloadFile(url, destFile);
    }


    public static void downloadFile(String url, final File downloadedFile) {

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder().url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("downfile :  error ");
                downloadedFile.delete();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    BufferedSink sink = Okio.buffer(Okio.sink(downloadedFile));
                    sink.writeAll(response.body().source());
                    sink.close();
                    response.body().close();

                    System.out.println("downfile: " + downloadedFile.getAbsolutePath());

                    if (downloadedFile.length() < 1024 * 10) {
                        downloadedFile.delete();
                        System.out.println("empty file deleted : " + downloadedFile.getAbsolutePath());
                    } else {

//                        if(bw!=null){
//                            bw.write(url+"\n");
//                        }
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                    downloadedFile.delete();
                }
            }
        });


    }
}
